<template>
  <div v-if="show" class="backTop flex_c_c" @click="backTop">
    <slot>^</slot>
  </div>
</template>

<script>
export default {
  props: {
    top: {
      type: Number,
      default: 800,
    },
  },
  data() {
    return {
      show: false,
    };
  },
  methods: {
    scrollHandle() {
      // 当网页卷上去的距离大于top指定距离，则要显示backTop,则把show改为true
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop >= this.top) {
        this.show = true;
      } else {
        this.show = false;
      }
    },
    backTop() {
      document.documentElement.scrollTop = document.body.scrollTop = 0;
    },
  },
  mounted() {
    document.addEventListener("scroll", this.scrollHandle);
  },
  destroyed() {
    document.removeEventListener("scroll", this.scrollHandle);
  },
};
</script>

<style lang="scss" scoped>
$ui-width: 720;
$num: 15;
$baseFontSize: 50; // 750 / 15
@function px2rem($px) {
  @return $px / $baseFontSize + rem;
}

.backTop {
  position: fixed;
  right: 20px;
  bottom: 100px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ccc;
  border-radius: 50%;
  border: 1px solid #ccc;
  box-shadow: 0 0 8px #ccc;
  color: #fff;
  font-size: px2rem(34);
}
</style>
